<!-- 实习管理-实习调动 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb"> </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space size="large">
          <a-select
            placeholder="请选择组织"
            :default-value="1"
            :style="{ width: '200px' }"
          >
            <a-option :value="1">全部</a-option>
            <a-option>Shanghai</a-option>
            <a-option>Guangzhou</a-option>
            <a-option disabled>Disabled</a-option>
          </a-select>
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="搜索员工名字/工号"
          />
        </a-space>
      </template>
      <template #right>
        <a-button type="primary" @click="confirm(null)">
          批量确认调动
        </a-button>
      </template>
    </ConditionBox>
    <TableTurn
      :tableData="getTableData"
      :args="args"
      ref="tableRef"
      :isShowPagination="false"
    >
      <a-table-column :width="60" title="序号">
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
      />
      <a-table-column title="异动类型" data-index="status" fixed="right">
        <template #cell="{ record: { internshipChanges } }">
          {{ internshipChanges === 1 ? '实习转试用' : '实习转正式' }}
        </template>
      </a-table-column>
      <a-table-column title="审批状态" data-index="status" :width="150">
        <template #cell="{ record: { status } }">
          <a-tag
            class="enable"
            :color="
              status === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                status === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))',
              '--enable':
                status === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))'
            }"
          >
            {{ status === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column :width="100" title="操作" fixed="right">
        <template #title>
          <a-tooltip content="是否显示排序">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="isFilter"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-space>
            <a-tooltip content="查看详情">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="
                  router.push({
                    name: 'HumanRosterDetail',
                    query: {
                      id: record.id
                    }
                  })
                "
              />
            </a-tooltip>
            <a-popconfirm content="是否确认调动该员工?" @ok="confirm(record)">
              <a-button type="text">确认调动</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <FormHeaderControlSetting
    title="实习调动表头设置"
    v-model:visible="modalVisiable"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
</template>

<script lang="tsx" setup>
import { GetUserList } from '@/apis/management/user/index';
import { GetBusinessModalData } from '@/apis/controltotal';
import {
  GetPracticeChangeList,
  ConfirmPracticeChange,
  ChangePracticeStatus,
  ChangePratice2Probation,
  ChangePratice2Confirm,
  ChangePraticeDate
} from '@/apis/management/personnel/changeManagement/index';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';

import {
  PostImportTemplate,
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import HumenNumberCard from '@/components/HumenNumberCard/index.vue';
import { getPositionList, getFlatDept } from '@/utils/common';
import TableStateMethod from './Components/TableStateMethod/index.vue';
import IntershipChange from './Components/IntershipChange/index.vue';
import IntershipProof from './Components/IntershipProof/index.vue';
import { Message, Modal } from '@arco-design/web-vue';

const router = useRouter();
const title = '实习调动';
const breadCrumb: string[] = ['人事', '异动管理', '实习调动'];
let currPracticeTime = ref(''); // 当前实习时间

let tableRef = ref();

/* 储存选择表格的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

// 新增表头
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    })) as any;

    let headerListCode: any = [];
    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 13,
      headerListCode: headerListCode.join(',')
    });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

const getTableData = async (page: any) => {
  try {
    const res = await GetPracticeChangeList({
      ...page
    });
    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

let headerSetting = ref<any>([]), // 当前的表头数据
  orginHeaderList = ref([]), // 原始的表头数据
  deptList = ref([]), // 平级部门数据
  positionList = ref([]);
// 获取其他数据
const getData = async () => {
  try {
    const userId = +(localStorage.getItem('userId') as string);
    const [headerSettingRes, deptRes, positionListRes, businessModalDataRes] =
      await Promise.all([
        // 获取人员表头
        GetHeaderSetting({
          ownerFuncType: 13,
          userId
        }),
        // 获取平级的组织数据
        getFlatDept(),
        // 获取所有职位数据
        getPositionList(),
        // 获取控件人员数据
        GetBusinessModalData({
          funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
        })
      ]);
    orginHeaderList.value = headerSettingRes;
    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    // exportHeaderList.value = headerSetting.value;
    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
    deptList.value = deptRes;
    positionList.value = positionListRes.content;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let modalVisiable = ref(false); // 判断是否显示表头

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    modalVisiable.value = !modalVisiable.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将组织名称移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 13,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'CB4163C72FA5E45D38302983E8A66801E',
  'CE183DF5A547A4728A60F9AFDF3C53194',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C50267C6B8E104B0C91EDD25BCAE35609',
  'C14A4E93E33754840ADDD083163AB7C68'
];

// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 性别
    case 'CEE710BACA80445DE9A39622878DF04A2':
      return (
        <div>
          {record['CEE710BACA80445DE9A39622878DF04A2'] == 1 ? '男' : '女'}
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            deptList.value.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 职位
    case 'C7341027925C943708F3AEF98703ECC47':
      return (
        <div>
          {
            positionList.value.find(
              (item: any) =>
                item.id == record['C7341027925C943708F3AEF98703ECC47']
            )?.name
          }
        </div>
      );
    // 实习期
    case 'C14A4E93E33754840ADDD083163AB7C68':
      return (
        <div>
          {record['C14A4E93E33754840ADDD083163AB7C68']?.split(',').join(' ~ ')}
        </div>
      );
    // 出生日期、入职时间
    case 'C4869FD6FEC404979A6F73A14DFA07E78' ||
      'CC0D5415792B24BBCAD7DF5AB8A25A0AB':
      return (
        <div>
          {ctlCode == 'C4869FD6FEC404979A6F73A14DFA07E78'
            ? record['C4869FD6FEC404979A6F73A14DFA07E78']?.slice(2, -2)
            : record['CC0D5415792B24BBCAD7DF5AB8A25A0AB']?.slice(2, -2)}
        </div>
      );
    default:
      break;
  }
};

const confirm = async (record: any | null) => {
  try {
    if (record) {
      await ConfirmPracticeChange({
        ids: [record.id],
        type: record.internshipChanges
      });
      await ChangePracticeStatus({
        ids: [record.id],
        type: 3
      });
    } else {
      if (!selectedList.value.length) {
        Message.error('请选择要调动的员工');
        return;
      }
      Modal.confirm({
        title: '是否确认调动',
        content: '是否确认调动选中的员工?',
        onOk: async () => {
          await ConfirmPracticeChange({
            ids: selectedList.value,
            type: record.internshipChanges
          });
          await ChangePracticeStatus({
            ids: selectedList.value,
            type: 3
          });
        }
      });
    }
    refresh();
  } catch (error) {
    console.log(error);
  }
};

const refresh = (page?: any) => {
  tableRef.value.loadData(page);
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px 20px;
  .box {
    margin-bottom: 16px;
    display: flex;
    &-item {
      width: 0;
      flex: 1;
      // width: 400px;
      // display: flex;
    }
    &-item:not(:last-child) {
      margin-right: 16px;
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    &-front {
      position: relative;
      line-height: 30px;
      margin-right: 16px;
    }
  }
  .main {
    margin-top: 20px;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
.ggg {
  display: flex;
  overflow-x: auto;
  width: 100%;
}
</style>
